package org.wuhong.utils;


import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.time.LocalDate;
import java.util.Properties;

/**
 * @ClassName NioUploadUtil
 * @Description TODO
 * @Author director吴
 * @Date 2022/2/10 12:00
 * @Version 1.0
 **/

public class NioUploadUtil {

    /**
     * NIO方式实现文件上传
     */


    //设置静态属性
    private static String uploalPath;

    //静态代码块注入上传路径
    static {
        YamlPropertiesFactoryBean yamlPropertiesFactoryBean = new YamlPropertiesFactoryBean();
        yamlPropertiesFactoryBean.setResources(new ClassPathResource("application.yml"));
        Properties properties = yamlPropertiesFactoryBean.getObject();
        uploalPath = properties.getProperty("file.uploadPath");
    }


    //Nio上传
    public static String upload(MultipartFile file) {
        String path = null;
        try {
            //获取FileInputStream，channel
            FileInputStream fileInputStream = (FileInputStream) file.getInputStream();
            FileChannel inputChannel = fileInputStream.getChannel();
            ByteBuffer buffer = ByteBuffer.allocate((int) file.getSize());

            //写入到buffer
            int i = inputChannel.read(buffer);

            /*
                1.生成文件File对象
                2.-采用uploadPath配置文件属性+时间格式(yyyy-DD)+文件名
             */
            File file2 = new File(uploalPath + "\\" + LocalDate.now().toString().substring(0, 7).toString() + "\\" + SnowIDUtil.snowflakeId() + file.getOriginalFilename());

            path = file2.getPath();
            File parentFile = file2.getParentFile();
            if (!parentFile.exists()) {
                parentFile.mkdirs();
                if (!file2.exists()) {
                    file2.createNewFile();
                }
            }
            FileOutputStream fileOutputStream = new FileOutputStream(file2);
            FileChannel channel2 = fileOutputStream.getChannel();

            //从buffer写出到服务器上
            buffer.flip();
            channel2.write(buffer);

            fileInputStream.close();
            fileOutputStream.close();

        } catch (IOException e) {
            e.printStackTrace();
        }


        return path;
    }


}
